#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <atomic>
#include <memory>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>

#include <boost/algorithm/string.hpp>
#include <jsoncpp/json/json.h>


namespace ns_util
{
    const std::string temp_path = "./temp/";

    class TimeUtil
    {
    public:
        static std::string GetTimeStamp()
        {
            struct timeval _time;
            gettimeofday(&_time, nullptr);
            return std::to_string(_time.tv_sec);
        }
        static std::string GetTimeMs()
        {
            struct timeval _time;
            gettimeofday(&_time, nullptr);
            return std::to_string(_time.tv_sec * 1000 + _time.tv_usec / 1000);
        }
    };

    class PathUtil
    {
    public:
        static std::string AddSuffix(const std::string &file_name, const std::string &suffix)
        {
            std::string path_name = temp_path;
            path_name += file_name;
            path_name += suffix;
            return path_name;
        }
        static std::string CompilerError(const std::string &file_name)
        {
            return AddSuffix(file_name, ".compile_error");
        }
        // 构建源文件路径+后缀的完整路径
        static std::string Src(const std::string &file_name)
        {
            return AddSuffix(file_name, ".cpp");
        }
        // 构建可执行文件路径+后缀的完整路径
        static std::string Exe(const std::string &file_name)
        {
            return AddSuffix(file_name, ".exe");
        }
        // 构建该程序对应的标准错误文件路径+后缀的完整路径
        static std::string Stdin(const std::string &file_name)
        {
            return AddSuffix(file_name, ".stdin");
        }
        // 构建该程序对应的标准错误文件路径+后缀的完整路径
        static std::string Stdout(const std::string &file_name)
        {
            return AddSuffix(file_name, ".stdout");
        }
        // 构建该程序对应的标准错误文件路径+后缀的完整路径
        static std::string Stderr(const std::string &file_name)
        {
            return AddSuffix(file_name, ".stderr");
        }
    };

    class FileUtil
    {
    public:
        static bool IsFileExists(const std::string& path_name)
        {
            struct stat st;
            if (stat(path_name.c_str(), &st) == 0) {
                // 该文件存在
                return true;
            }
            return false;
        }
        static std::string UniqueFileName()
        {
            std::string ms = TimeUtil::GetTimeMs();

            std::atomic_int id(0);
            id++;
            std::string uniq_id = std::to_string(id);

            return ms + "_" + uniq_id;
        }

        static bool WriteFile(const std::string &target, std::string &content)
        {
            std::ofstream out(target);
            if (!out.is_open()) {
                return false;
            }
            out.write(content.c_str(), content.size());
            out.close();
            return true;
        }
        static bool ReadFile(const std::string &target, std::string *content, bool keep = false)
        {
            std::ifstream in(target);
            if (!in.is_open()) {
                return false;
            }
            //std::cout << "target" << target << std::endl;
            std::string line;
            while (std::getline(in, line)) {
                (*content) += line;
                (*content) += (keep ? "\n" : "");
                //std::cout << "line" << line << std::endl;
            }
            
            in.close();
            return true;
        }
    };

    class JsonUtil
    {
    public:
        //  实现数据的序列化
        static bool serialize(const Json::Value &val, std::string *out)
        {
            std::stringstream ss;

            // 先实例化一个工厂化对象
            Json::StreamWriterBuilder swb;
            // 设置输出格式为UTF-8,使得中文字符能被正常输出
            swb.settings_["emitUTF8"] = true;

            // 通过工厂类对象来生产类对象
            std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
            int ret = sw->write(val, &ss);
            if (ret != 0)
            {
                //LOG(ERROR) << "Failed to write JSON data" << "\n";
                std::cerr << "Failed to write JSON data" << std::endl;
                return false;
            }
            *out = ss.str();
            return true;
        }

        // 实现json字符串的反序列化
        static bool deserialize(const std::string &in, Json::Value &val)
        {
            // 实例化工厂类对象
            Json::CharReaderBuilder crb;
            // 生产CharReader对象
            std::string errs;
            std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
            bool ret = cr->parse(in.c_str(), in.c_str() + in.size(), &val, &errs);
            if (ret == false)
            {
                //LOG(ERROR) << "Failed to parse JSON data:" << errs << "\n";
                std::cerr << "Failed to parse JSON data:" << errs << std::endl;
                return false;
            }
            return true;
        }
    };

    class StringUtil
    {
    public:
        /**
         * str：输入型，目标切分字符串
         * target：输出型，保存切分好的字符串
         * sep：指定的分割符
         */
        static void StringSpilt(const std::string &str, std::vector<std::string> *target, std::string sep)
        {
            boost::split((*target), str, boost::is_any_of(sep), boost::algorithm::token_compress_on);
        }
    };

}